package com.hytech.licenseplate;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.hytech.utilities.EULAActivity;
import com.hytech.utilities.InfoActivity;

public class LicensePlateActivity extends ListActivity {
    
	// we arn't using an enum here because they bloat a bit.

	// This is for choosing which license plate list to use.  Currently we 
	// only have one, so it'll work as a "refresh" 
	private static final int CHOOSE_LIST_ID = Menu.FIRST;
	
	// This is to not display checked off names. 
	private static final int SHOW_REMOVED_NAMES_ID = CHOOSE_LIST_ID + 1;
	
	// A page of simple data about the app and me.  
	private static final int INFO_ID = SHOW_REMOVED_NAMES_ID + 1;
	
	private static final String PREFERENCE_FILE_NAME = "Preferences";
	private static final String SHOW_REMOVED_NAMES_KEY = "Show_Removed_Name";

	// this is our database helper. 
	private LicenseDbAdapter mDbHelper;
	
	boolean mShowRemovedNames;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.licensemain);
        
        // first check the EULA.  
        if (EULAActivity.checkEula(this, R.raw.eula)) {

        	// we'll be using a database here. 
            mDbHelper = new LicenseDbAdapter(this);
            mDbHelper.open();
            
            // Restore preferences
            SharedPreferences settings = getSharedPreferences(PREFERENCE_FILE_NAME, 0);
            mShowRemovedNames = settings.getBoolean(SHOW_REMOVED_NAMES_KEY, true);
            
            // fill the data from the Database.
            showList();	
        }
        
        
    }
    
    public void EULAAccepted() {
    	
    }
    
    // This creates the Options Menu, nice and easy.  
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, CHOOSE_LIST_ID, 0, R.string.choose_list);
        menu.add(0, SHOW_REMOVED_NAMES_ID, 0, R.string.display_checked_items);
        menu.add(0, INFO_ID, 0, R.string.info);
        return true;
    }

    // This responds to something being picked on the Options Menu. 
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case CHOOSE_LIST_ID:
                createChooseListDialog();
                return true;
            
            case SHOW_REMOVED_NAMES_ID:
            	toggleRemovedNames();
            	return true;
            
            case INFO_ID:
            	openInfo();
            	return true;
            	
            default: 
            	break;
        }

        return super.onMenuItemSelected(featureId, item);
    }
    
    // This is a function for choosing a new list.  Right now it needs to load a dialog.
    private void createChooseListDialog() {
    	// first we need to  decide which target to load.
    	
    	final int maxNames = 3;
    	
    	// and to do that we need the name of each list. 
    	String[] listNames = new String[maxNames];
    	int numOfNames = 0;
    	
    	final Resources resources = getResources();

    	// we'll use an input stream to read the resources. 
        InputStream inputStream = resources.openRawResource(R.raw.licenselists);
        
        // Now transform to a buffer reader.  
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        try{
	        String nextLine;
	        // while there's still names coming out... and the num of names hasn't already reached the max. 
	        while ((nextLine = reader.readLine()) != null && numOfNames < maxNames) {
	            if (nextLine.charAt(0) == '#') { 
	            	listNames[numOfNames] = nextLine.substring(1);
	            	numOfNames++;
	            }
	        }
	        
	        
        } catch (IOException e) {
			throw new RuntimeException(e);
    	}
    	
        // do we have a list? 
        if ( numOfNames > 0 ) {
        	AlertDialog.Builder listSelector = new AlertDialog.Builder(this);
        	
        	// don't think we need the icon. 
        	// alt_bld.setIcon(R.drawable.icon);
        	
        	listSelector.setTitle("Select a License Plate List");
        	listSelector.setSingleChoiceItems(listNames, -1, new DialogInterface.OnClickListener() {

        		public void onClick(DialogInterface dialog, int item) {
        			switchList(item);
        			dialog.dismiss();
        		}
        	});
        	
        	AlertDialog alert = listSelector.create();
        	alert.show();
	
        } else {
        	// no list names, just use 0.
        	switchList(0);
        }
    	
    	
    }
    
    // this is a call back from our alert dialog..  This clears the actual database, and then loads the list. and a simple refresh. 
    public void switchList(int listNumber) {
    	// maybe throw in a progress bar here...
    	// We don't clear the database until we know we have a new list.
    	mDbHelper.clearDatabase();
    	mDbHelper.loadTargetList(listNumber);
    	showList();
    }
    
    // toggles the removed name preference. 
    private void toggleRemovedNames() {

    	// flip the bit first. 
    	mShowRemovedNames = !mShowRemovedNames;
    	 // load the preferences. 
        SharedPreferences settings = getSharedPreferences(PREFERENCE_FILE_NAME, 0);
        // we need to edit, so let's open this. 
        SharedPreferences.Editor settingsEditor = settings.edit();
        // put the boolean in the settings file. 
        settingsEditor.putBoolean(SHOW_REMOVED_NAMES_KEY, mShowRemovedNames);
        // commit the changes. 
        settingsEditor.commit();
        
        showList();
    }
    
    // This is the function to open the info page for the application.
    private void openInfo(){
    
    	// Launch Eula activity
		Intent i = new Intent(this, InfoActivity.class);
		
		// check the bundle. 
		Bundle b = i.getExtras();
		
		b.putInt(InfoActivity.INFO_ID, R.raw.info );
		
		LicensePlateActivity.this.startActivity(i);
		
    }

    @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
    	MenuItem removedNameMenuItem = menu.findItem(SHOW_REMOVED_NAMES_ID);
    	if ( mShowRemovedNames ) {
    		removedNameMenuItem.setTitle(R.string.hide_checked_items);
    	} else {
    		removedNameMenuItem.setTitle(R.string.display_checked_items);
    	}
		return super.onPrepareOptionsMenu(menu);
	}

	// This is my generic populate list.  Rather than manipulate the screen to 
    // keep it syncronized with the data, just read in the data again, it should
    // be fast enough.  (And kept speedy)
    private void showList() {
    	
    	String new_title = "License Plate Game.  Score: " + mDbHelper.getSelectedRecords() + "/" + mDbHelper.getTotalRecords(); 
    	setTitle(new_title);
    	
        // Get all of the rows from the database and create the item list
    	Cursor mStateCursor = mDbHelper.fetchCurrentState(mShowRemovedNames);
        startManagingCursor(mStateCursor);

        // create an array of the fields to add to the list. 
        String[] from = new String[]{LicenseDbAdapter.KEY_CHECK, LicenseDbAdapter.KEY_NAME};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.check, R.id.check};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter licenses = 
            new SimpleCursorAdapter(this, R.layout.licenserow, mStateCursor, from, to);
        
        licenses.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            	
            	// let's start by getting the check column info. 
            	int check_Column = cursor.getColumnIndexOrThrow(LicenseDbAdapter.KEY_CHECK);
            	
            	// is this the column we're working on? 
                if(check_Column == columnIndex) {
                	// then this view is a checkbox. 
                    CheckBox cb = (CheckBox)view;
                    // and this needs to be marked as checked. 
                    cb.setChecked( cursor.getInt(check_Column) == 0 ? false:true);
                    return true;
                }
                
                // let's start by getting the name column info. 
                int name_Column = cursor.getColumnIndexOrThrow(LicenseDbAdapter.KEY_NAME);
                // now is this the column we're working on
                if(name_Column == columnIndex) {
                	// still a checkbox. 
                	CheckBox cb = (CheckBox)view;
                	
                	// ok first publish the name. 
            		cb.setText(cursor.getString(name_Column));
            		
            		// but first we need to check the cursor to see if this has been checked off.                 	
                	if ( cursor.getInt(check_Column) == 1) {
                	
                		// let's mark it as a strike through.
                		cb.setPaintFlags( cb.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                	} else {
                		// let's make sure it isn't marked as a strike through.  With out this some stuff gets marked.
                		cb.setPaintFlags( cb.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
                	}
 
                	return true;
                }
                
            return false;
            }
        });

        // set this new list adapter to the Listactivity. 
        setListAdapter(licenses);

    }

    // this is hardly a responsive click, but it works.  
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
	
		// let's find the checkbox we're on.
		// the view is the current row, the listview is the whole screen.
		CheckBox targetCheckBox = (CheckBox) v.findViewById(R.id.check);

		// ok update the database with the new data. 
		mDbHelper.updateNote(id, !targetCheckBox.isChecked());
		
		// update the list now.
		showList();
		
	}

}